package top.jacktgq.itheima.netty.protocol_design.groupchat.rpc;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.itheima.netty.protocol_design.groupchat.message.RpcResponseMessage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author CandyWall
 * @Date 2021/3/25--16:18
 * @Description
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {
    public static final Map<Integer, Promise<Object>> PROMISE_MAP = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) {
        log.debug("调用结果：{}", msg);
        // 从集合中获取并移除返回结果的Promise对象
        Promise<Object> promise = PROMISE_MAP.remove(msg.getSequenceId());
        String errorMsg = null;
        if (promise != null) {
            Object returnValue = msg.getReturnValue();
            errorMsg = msg.getErrorMsg();
            if (returnValue != null) {
                promise.setSuccess(returnValue);
            } else {
                promise.setFailure(new Exception(errorMsg));
            }

        }

    }

}
